import React,{ useEffect, useState } from 'react';
import { Toast } from 'antd-mobile';

/**
 * 历史收货人方式身份验证
 * @param {*} props 
 * @returns 
 */
function IntCode (props){

    const { 
        name='', txtCodeTime, setTextCode, intValue, setValue, maxLen,
        placeholder, icon, doChange, doFocus, doValid, desc, currentName='', getCode,
        onBlur
    } = props;

    const [ isError, setIsError ] = useState(false);
    // 禁用重新获取
    const [ distableBtn, setDisableBtn ] = useState(false);

    useEffect(() => {}, [ intValue, isError ]);

    const onFocus = (e) => {
        doFocus(e);
    }

    const setCode = () => {
        if(distableBtn) return;
        let idx = 60;
        const intervalId = setInterval(() => {
            setDisableBtn(true);
            setTextCode(idx + 's 重新获取');
            idx--;
            if(idx <=0) {
                setDisableBtn(false);
                clearInterval(intervalId);
                setTextCode('获取验证码');
            }
        }, 1000);
    }

    const doCheck = () => {
        if(getCode && getCode()) {
            setCode();
        }
    }

    const doBlur = e => {
        if(doValid && !doValid(e.target.value)) {
            Toast.show({ content: desc });
            setIsError(true);
        } else {
            setIsError(false)
        }
        onBlur(e);
    }

    const onChange = e => {
        doChange(e);
        if(doValid && !doValid(e.target.value)) {
            setIsError(true);
        } else {
            setIsError(false)
        }
    }

    return (
        <div data-v2310001='' className='w-int-box'>
            <div className={`w-int-body${isError ? ' w-error' : ''}`}>
                <i className='w-label-icon' children={icon}/>
                <input data-v2310001='' name={name} value={intValue} maxLength={maxLen}
                    className='w-int-inner' placeholder={placeholder} autoComplete='off'
                    onBlur={e => doBlur(e)} onFocus={e => onFocus(e)} onChange={e => onChange(e)}
                />
                { 
                    name !== '' && name === currentName ? (
                        <i data-v2310001='' className='w-ibtn w-int-clear' onClick={() => setValue('')}/>
                    ) : null 
                }
            </div>
            <button data-v2310001='' className={`w-code-btn${distableBtn ? ' w-disable' : ''}`}
                disabled={distableBtn} children={ txtCodeTime } onClick={()=> doCheck()}/>
        </div>
    )
}
export default IntCode;